"""
简化的文档转换器
专门处理PDF和Word文档转换为Markdown格式
避免复杂的网络依赖，使用本地库
"""

import os
import re
from typing import Optional, Union

# 基础文档转换结果类
class DocumentConverterResult:
    def __init__(self, text_content: str = "", title: str = ""):
        self.text_content = text_content
        self.title = title

class SimpleDocumentConverter:
    """简化的文档转换器，专门处理PDF和Word"""
    
    def __init__(self):
        self.supported_formats = ['.pdf', '.docx', '.doc']
    
    def convert(self, file_path: str) -> DocumentConverterResult:
        """
        转换文档为Markdown格式
        
        Args:
            file_path (str): 文件路径
            
        Returns:
            DocumentConverterResult: 转换结果
        """
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        file_ext = os.path.splitext(file_path)[1].lower()
        
        if file_ext == '.pdf':
            return self._convert_pdf(file_path)
        elif file_ext in ['.docx', '.doc']:
            return self._convert_word(file_path)
        else:
            raise ValueError(f"不支持的文件格式: {file_ext}")
    
    def _convert_pdf(self, file_path: str) -> DocumentConverterResult:
        """转换PDF文档"""
        try:
            import pdfplumber
            
            markdown_content = []
            title = os.path.splitext(os.path.basename(file_path))[0]
            
            with pdfplumber.open(file_path) as pdf:
                markdown_content.append(f"# {title}\n")
                
                for page_num, page in enumerate(pdf.pages, 1):
                    # 提取文本
                    text = page.extract_text()
                    if text:
                        # 简单的文本清理
                        text = self._clean_text(text)
                        markdown_content.append(f"## 第{page_num}页\n")
                        markdown_content.append(f"{text}\n\n")
                    
                    # 提取表格
                    tables = page.extract_tables()
                    if tables:
                        for i, table in enumerate(tables, 1):
                            if table:
                                markdown_content.append(f"### 表格 {i}\n")
                                markdown_content.append(self._table_to_markdown(table))
                                markdown_content.append("\n")
            
            return DocumentConverterResult(
                text_content="".join(markdown_content),
                title=title
            )
            
        except ImportError:
            raise ImportError("需要安装 pdfplumber 库: pip install pdfplumber")
        except Exception as e:
            raise Exception(f"PDF转换失败: {e}")
    
    def _convert_word(self, file_path: str) -> DocumentConverterResult:
        """转换Word文档"""
        title = os.path.splitext(os.path.basename(file_path))[0]
        
        # 方法1: 尝试使用python-docx
        try:
            return self._convert_word_docx(file_path, title)
        except ImportError:
            pass
        except Exception as e:
            print(f"使用python-docx转换失败: {e}")
        
        # 方法2: 尝试使用mammoth (如果可用)
        try:
            return self._convert_word_mammoth(file_path, title)
        except ImportError:
            pass
        except Exception as e:
            print(f"使用mammoth转换失败: {e}")
        
        # 如果所有方法都失败
        raise Exception("无法转换Word文档，请确保安装了 python-docx 或 mammoth 库")
    
    def _convert_word_docx(self, file_path: str, title: str) -> DocumentConverterResult:
        """使用python-docx转换Word文档"""
        try:
            from docx import Document
            
            doc = Document(file_path)
            markdown_content = [f"# {title}\n\n"]
            
            for paragraph in doc.paragraphs:
                if paragraph.text.strip():
                    # 根据段落样式转换为Markdown
                    text = paragraph.text.strip()
                    style_name = paragraph.style.name if paragraph.style else ""
                    
                    if 'Heading 1' in style_name:
                        markdown_content.append(f"# {text}\n\n")
                    elif 'Heading 2' in style_name:
                        markdown_content.append(f"## {text}\n\n")
                    elif 'Heading 3' in style_name:
                        markdown_content.append(f"### {text}\n\n")
                    else:
                        markdown_content.append(f"{text}\n\n")
            
            # 处理表格
            for table in doc.tables:
                markdown_content.append(self._docx_table_to_markdown(table))
                markdown_content.append("\n")
            
            return DocumentConverterResult(
                text_content="".join(markdown_content),
                title=title
            )
            
        except ImportError:
            raise ImportError("需要安装 python-docx 库: pip install python-docx")
    
    def _convert_word_mammoth(self, file_path: str, title: str) -> DocumentConverterResult:
        """使用mammoth转换Word文档"""
        try:
            import mammoth
            
            with open(file_path, "rb") as docx_file:
                result = mammoth.convert_to_markdown(docx_file)
                
            markdown_content = f"# {title}\n\n{result.value}"
            
            return DocumentConverterResult(
                text_content=markdown_content,
                title=title
            )
            
        except ImportError:
            raise ImportError("需要安装 mammoth 库: pip install mammoth")
    
    def _clean_text(self, text: str) -> str:
        """清理文本"""
        if not text:
            return ""
        
        # 移除多余空行
        text = re.sub(r'\n\s*\n\s*\n', '\n\n', text)
        
        # 移除行首行尾空格
        lines = [line.strip() for line in text.split('\n')]
        
        return '\n'.join(lines)
    
    def _table_to_markdown(self, table) -> str:
        """将表格转换为Markdown格式"""
        if not table or not table[0]:
            return ""
        
        markdown_rows = []
        
        # 表头
        if table[0]:
            header = "| " + " | ".join(str(cell) if cell else "" for cell in table[0]) + " |"
            separator = "|" + "|".join(" --- " for _ in table[0]) + "|"
            markdown_rows.append(header)
            markdown_rows.append(separator)
        
        # 数据行
        for row in table[1:]:
            if row:
                row_text = "| " + " | ".join(str(cell) if cell else "" for cell in row) + " |"
                markdown_rows.append(row_text)
        
        return "\n".join(markdown_rows) + "\n"
    
    def _docx_table_to_markdown(self, table) -> str:
        """将docx表格转换为Markdown格式"""
        markdown_rows = []
        
        rows = table.rows
        if not rows:
            return ""
        
        # 表头
        header_cells = [cell.text.strip() for cell in rows[0].cells]
        if header_cells:
            header = "| " + " | ".join(header_cells) + " |"
            separator = "|" + "|".join(" --- " for _ in header_cells) + "|"
            markdown_rows.append(header)
            markdown_rows.append(separator)
        
        # 数据行
        for row in rows[1:]:
            cells = [cell.text.strip() for cell in row.cells]
            if any(cells):  # 只有当行中有内容时才添加
                row_text = "| " + " | ".join(cells) + " |"
                markdown_rows.append(row_text)
        
        return "\n".join(markdown_rows) + "\n"


# 便捷函数
def convert_document_to_markdown(file_path: str, output_path: Optional[str] = None) -> str:
    """
    将文档转换为Markdown格式
    
    Args:
        file_path (str): 输入文件路径
        output_path (str, optional): 输出文件路径，如果不提供则返回内容
        
    Returns:
        str: Markdown内容
    """
    converter = SimpleDocumentConverter()
    result = converter.convert(file_path)
    
    if output_path:
        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(result.text_content)
        
        print(f"✅ 转换完成: {output_path}")
    
    return result.text_content


if __name__ == "__main__":
    # 测试代码
    import sys
    
    if len(sys.argv) > 1:
        input_file = sys.argv[1]
        output_file = sys.argv[2] if len(sys.argv) > 2 else None
        
        try:
            content = convert_document_to_markdown(input_file, output_file)
            if not output_file:
                print(content)
        except Exception as e:
            print(f"转换失败: {e}")
    else:
        print("使用方法: python document_converter.py <输入文件> [输出文件]")
